package com.rc.evcharger.service;

import com.github.dozermapper.core.Mapper;
import com.rc.evcharger.common.constant.level.UserLevelConstant;
import com.rc.evcharger.mapper.elec.ElecGunMapper;
import com.rc.evcharger.mapper.elec.ElecPileMapper;
import com.rc.evcharger.mapper.order.OrderInfoMapper;
import com.rc.evcharger.model.elec.ElecGun;
import com.rc.evcharger.model.elec.ElecPile;
import com.rc.evcharger.model.hlht.HlhtOrderInfo;
import com.rc.evcharger.model.hlhtsk.HlhtskTenant;
import com.rc.evcharger.model.order.OrderInfo;
import com.rc.evcharger.redis.RedChargeDataService;
import com.rc.evcharger.service.discount.TenantDiscountPolicyService;
import com.rc.evcharger.service.hlht.HlhtOrderInfoService;
import com.rc.evcharger.service.hlhtsk.HlhtskTenantService;
import com.rc.evcharger.vo.charge.CommandStopReq;
import com.rc.evcharger.vo.cost.UserLevelPriceResult;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * 正向互联订单结算
 * Created by Sven on 2021/05/15
 */
@Service
//@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class HlhtOrderCostServiceImpl implements HlhtOrderCostService {
    private static Logger logger = LogManager.getLogger(HlhtOrderCostServiceImpl.class);

    @Autowired
    private Mapper dozerMapper;

    //@Autowired
    //private TenantService tenantService;

    @Autowired
    private HlhtskTenantService hlhtskTenantService;

    @Autowired
    private HlhtOrderInfoService hlhtOrderInfoService;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private RedChargeDataService redChargeDataService;

    @Autowired
    private ElecPileMapper elecPileMapper;

    @Autowired
    private ElecGunMapper elecGunMapper;

    @Autowired
    private TenantDiscountPolicyService tenantDiscountPolicyService;

    @Override
    public synchronized void updateOrderCostInnerHlht1(CommandStopReq commandStopReq, OrderInfo oooorderInfo) {
        logger.info(commandStopReq.getTenantCode() + "-" + commandStopReq.getHlhtTenantCode() + ":内联反向互联互通用户【0个人钱包】订单结算,会员ID:{},内部订单号:{},外部订单号:{}",
                oooorderInfo.getMemberId(), oooorderInfo.getOrderNum(), oooorderInfo.getOutOrderNum());
        OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(oooorderInfo.getOrderId());


        ElecPile elecPile = elecPileMapper.selectByPrimaryKey(orderInfo.getElecPileId());
        ElecGun elecGun = elecGunMapper.selectByPrimaryKey(orderInfo.getElecGunId());

        //orderInfo转换HlhtOrderInfo,total_money为原价，没有改动
        HlhtOrderInfo updateHlhtOrderInfo = dozerMapper.map(orderInfo, HlhtOrderInfo.class);

        //以下字段要反过来:内联正向+内联反向
        updateHlhtOrderInfo.setTenantCode(commandStopReq.getHlhtTenantCode());
        updateHlhtOrderInfo.setHlhtTenantCode(commandStopReq.getTenantCode());
        updateHlhtOrderInfo.setHlhtOrderType("1");//互联互通订单类型以tenant_code为基准,0为自主订单 1反向对接订单 2正向对接订单, 默认0

        //互联用户ID
        //Tenant tenant = tenantService.selectByPrimaryKey(commandStopReq.getTenantCode());
        //updateHlhtOrderInfo.setMemberId(tenant.getMemberId());//按瑞晨互联用户

        //hlhtsk_tenant.hlht_member_id:互联会员ID,属于tenant_code（由瑞晨平台方审核通过时自动创建，这个用户不能登录）,代表hlht_tenant_code,内部互联时需要
        //按设备商+运营商查找
        //tenantCode  设备方运营商
        //hlhtTenantCode SAAS内互联互通时对方运营商
        HlhtskTenant hlhtskTenant = hlhtskTenantService.selectHlhtTenantCode(commandStopReq.getHlhtTenantCode(), commandStopReq.getTenantCode());
        updateHlhtOrderInfo.setMemberId(hlhtskTenant.getHlhtMemberId());//代表按瑞晨互联用户

        //运营商通过瑞晨充第三方
        if ("3".equals(orderInfo.getHlhtOrderType())) {
            updateHlhtOrderInfo.setTenantCode(orderInfo.getTenantCode());
            updateHlhtOrderInfo.setHlhtTenantCode(orderInfo.getHlhtTenantCode());

            HlhtskTenant hlhtskTenant0 = hlhtskTenantService.selectHlhtTenantCode(orderInfo.getTenantCode(), orderInfo.getHlhtTenantCode());
            updateHlhtOrderInfo.setMemberId(hlhtskTenant0.getHlhtMemberId());//代表按瑞晨互联用户
        }

        //读取Redids中的缓存信息
        BigDecimal power = redChargeDataService.getPower(elecPile.getPileRtua(), elecGun.getGunNum(), oooorderInfo.getOrderNum());
        BigDecimal baseAmount = redChargeDataService.getBaseAmount(elecPile.getPileRtua(), elecGun.getGunNum(), oooorderInfo.getOrderNum());
        BigDecimal serviceAmount = redChargeDataService.getServiceAmount(elecPile.getPileRtua(), elecGun.getGunNum(), oooorderInfo.getOrderNum());
        //BigDecimal soc = redChargeDataService.getSoc(elecPile.getPileRtua(), elecGun.getGunNum(), oooorderInfo.getOrderNum());
        //String lastA5Date = redChargeDataService.getChargeReportTime(elecPile.getPileRtua(), elecGun.getGunNum(), oooorderInfo.getOrderNum());
        //String stopMode = redChargeDataService.getStopMode(elecPile.getPileRtua(), elecGun.getGunNum(), oooorderInfo.getOrderNum());
        //String pileStopMode = redChargeDataService.getPileStopMode(elecPile.getPileRtua(), elecGun.getGunNum(), oooorderInfo.getOrderNum());

        //得到四舍五入后的服务费，基本电费，总价格 并赋值到order0中
        baseAmount = baseAmount.setScale(2, BigDecimal.ROUND_HALF_UP);
        serviceAmount = serviceAmount.setScale(2, BigDecimal.ROUND_HALF_UP);
        BigDecimal totalMoney = baseAmount.add(serviceAmount);

        //无优惠
        updateHlhtOrderInfo.setDiscountAmount(BigDecimal.ZERO);
        updateHlhtOrderInfo.setDiscountServiceAmount(BigDecimal.ZERO);

        //redis赋值，防止数据库未提交获取不到最新数据
        updateHlhtOrderInfo.setTotalPower(power);
        updateHlhtOrderInfo.setTotalMoney(totalMoney);
        updateHlhtOrderInfo.setPayAmount(totalMoney);
        updateHlhtOrderInfo.setTotalSeviceMoney(serviceAmount);
        updateHlhtOrderInfo.setDiscountServiceAmount(serviceAmount);
        updateHlhtOrderInfo.setTotalElecMoney(baseAmount);

        //调整价
        updateHlhtOrderInfo.setServiceAdjustDiscAmount(BigDecimal.ZERO);
        updateHlhtOrderInfo.setAdjustPayAmount(updateHlhtOrderInfo.getAdjustTotalMoney());


        //按瑞晨互联用户,计算折扣
        //updateOrderCostInnerHlht1(commandStopReq, oooorderInfo, updateHlhtOrderInfo, tenant.getMemberId());
        updateOrderCostInnerHlht1(commandStopReq, orderInfo, updateHlhtOrderInfo, hlhtskTenant.getHlhtMemberId());

        //保存互联互联订单
        hlhtOrderInfoService.updateByPrimaryKeySelective(updateHlhtOrderInfo);
    }

    /**
     * 重载方法
     */
    private void updateOrderCostInnerHlht1(CommandStopReq commandStopReq, OrderInfo oooorderInfo, HlhtOrderInfo updateHlhtOrderInfo, Long hlhtMemberId) {
        logger.info(commandStopReq.getTenantCode() + "-" + commandStopReq.getHlhtTenantCode() + ":内联反向互联互通用户【0个人钱包】订单结算,互联会员ID:{},内部订单号:{},外部订单号:{}",
                hlhtMemberId, oooorderInfo.getOrderNum(), oooorderInfo.getOutOrderNum());

        //原价折扣,在调整价的基础上进行折扣
        UserLevelPriceResult userLevelPriceResult = tenantDiscountPolicyService.selectHlhtValidDPolicyByEsId(updateHlhtOrderInfo);
        if (userLevelPriceResult.getType() == UserLevelConstant.ENTERPRISE_VIP) {
            //更新updateHlhtOrderInfo
            usePolicyByEnterpriseRelief(updateHlhtOrderInfo, userLevelPriceResult);
        }

        //设置订单互联互通调整值
        //oooorderInfo.setServiceAdjustAmount(oooorderInfo.getTotalSeviceMoney());
        //oooorderInfo.setServiceAdjustDiscAmount(BigDecimal.ZERO);

        //互联互通调整价设置
        //hlhtTenantOpenPriceService.adjustHlhtRelif(oooorderInfo);
        //互联互通折扣
        //if (userLevelPriceResult.getType() == UserLevelConstant.ENTERPRISE_VIP) {
        //    this.usePolicyByHlht(oooorderInfo, userLevelPriceResult);
        //}

        //在调整价的基础上进行折扣
        //UserLevelPriceResult userLevelPriceResult = tenantDiscountPolicyService.selectHlhtValidDPolicyByEsId(oooorderInfo);
        //this.usePolicyByHlht(oooorderInfo, userLevelPriceResult);

        //反向互联互通用户订单结算:只能使用个人钱包 个人钱包对应的曹操或者滴滴进行打折
        //memberAccount.setAccount(memberAccount.getAccount().subtract(oooorderInfo.getPayAmount()));
        //memberAccountMapper.updateMemberAccountByMemberId(memberAccount);

        //增加余额变动记录
        //MemberAccountRecord newMemberAccountRecord = new MemberAccountRecord(oooorderInfo, memberAccount.getAccount());
        //memberAccountRecordMapper.insertSelective(newMemberAccountRecord);

        //订单结算
        //orderInfoMapper.updateByPrimaryKeySelective(oooorderInfo);

        logger.info(commandStopReq.getTenantCode() + "-" + commandStopReq.getHlhtTenantCode() + ":内联反向互联互通用户订单【0个人钱包】结算成功,内部订单号={}, 外部订单号={},chargamout={}, basemount={}, servermount={},payAmount={},discountAmount={},power:{}"
                , oooorderInfo.getOrderNum(), oooorderInfo.getOutOrderNum(), oooorderInfo.getTotalMoney(), oooorderInfo.getTotalElecMoney(), oooorderInfo.getTotalSeviceMoney()
                , oooorderInfo.getPayAmount(), oooorderInfo.getDiscountServiceAmount(), oooorderInfo.getTotalPower());

        logger.info(commandStopReq.getTenantCode() + "-" + commandStopReq.getHlhtTenantCode() + ":（互联折扣后价格）内联反向互联互通用户订单【0个人钱包】结算成功,内部订单号={}, 外部订单号={},chargamout={}, basemount={}, servermount={}," +
                        "payAmount={},discountAmount={},power:{}"
                , updateHlhtOrderInfo.getOrderNum(), updateHlhtOrderInfo.getOutOrderNum(), updateHlhtOrderInfo.getTotalMoney(), updateHlhtOrderInfo.getTotalElecMoney(), updateHlhtOrderInfo.getTotalSeviceMoney()
                , updateHlhtOrderInfo.getPayAmount(), updateHlhtOrderInfo.getDiscountServiceAmount(), updateHlhtOrderInfo.getTotalPower());
    }

    /**
     * 更新优惠方案价.企业VIP服务费
     */
    private void usePolicyByEnterpriseRelief(HlhtOrderInfo updateHlhtOrderInfo, UserLevelPriceResult result) {
        //优惠的金额
        updateHlhtOrderInfo.setDiscountAmount(updateHlhtOrderInfo.getDiscountAmount().add(result.getDiscountAmount()));
        //实付金额
        updateHlhtOrderInfo.setPayAmount(updateHlhtOrderInfo.getPayAmount().subtract(result.getDiscountAmount()));
        //折后的服务费
        updateHlhtOrderInfo.setDiscountServiceAmount(updateHlhtOrderInfo.getTotalSeviceMoney().subtract(result.getDiscountAmount()));

        //添加优惠记录
        //OrderDiscountRecord orderDiscount = new OrderDiscountRecord();
        //orderDiscount.setTenantCode(order.getTenantCode());
        //orderDiscount.setOrderId(order.getOrderId());
        //orderDiscount.setDiscountId(result.getId());
        //orderDiscount.setDiscountAmount(result.getDiscountAmount());
        //orderDiscount.setDiscountName("企业折扣");
        //orderDiscount.setDiscountType(UserLevelConstant.ENTERPRISE_VIP + "");
        //orderDiscount.setCreatedTime(new Date());
        //orderDiscountRecordMapper.insertSelective(orderDiscount);
    }

    /**
     * 互联互通折扣
     */
    private void usePolicyByHlht(HlhtOrderInfo updateHlhtOrderInfo, UserLevelPriceResult result) {
        updateHlhtOrderInfo.setServiceAdjustDiscAmount(result.getDiscountAmount());
        updateHlhtOrderInfo.setAdjustPayAmount(updateHlhtOrderInfo.getAdjustTotalMoney().subtract(result.getDiscountAmount()));

        //添加优惠记录
        //OrderDiscountRecord orderDiscount = new OrderDiscountRecord();
        //orderDiscount.setTenantCode(order.getTenantCode());
        //orderDiscount.setOrderId(order.getOrderId());
        //orderDiscount.setDiscountId(result.getId());
        //orderDiscount.setDiscountAmount(result.getDiscountAmount());
        //orderDiscount.setDiscountName("互联互通折扣价");
        //orderDiscount.setDiscountType(UserLevelConstant.HLHT_DISCOUNT_PRICE + "");
        //orderDiscount.setCreatedTime(new Date());
        //orderDiscountRecordMapper.insertSelective(orderDiscount);
    }

}
